package logic

import (
	"context"
	"encoding/xml"
	"fmt"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackExpressBindNtfCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBackExpressBindNtfCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackExpressBindNtfCallbackLogic {
	return &BackExpressBindNtfCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BackExpressBindNtfCallbackLogic) BackExpressBindNtfCallback(req *types.WkStNtfReq) (resp []byte, err error) {
	var expressBackBindReq entity.ExpressBackBindReq
	bin, _ := xml.MarshalIndent(&SFReply{Head: "OK"}, "", "  ")

	if err := xml.Unmarshal([]byte(req.Pkg), &expressBackBindReq); err != nil {
		fmt.Printf("xml.Unmarshal error: %v\n", err)
	}

	// 根据快递单号查询订单
	order, err := l.svcCtx.Db.GetOrderBySFBillCode(expressBackBindReq.FirstWaybillNo)
	if err != nil {
		logx.Errorf("查询订单失败，请求体参数: %v, 错误: %v", expressBackBindReq, err)
		return bin, nil
	}

	expressBind := new(entity.ExpressBind)
	expressBind.OrderId = uint(order.ID)
	expressBind.FirstCustomOrderCode = expressBackBindReq.FirstCustomOrderCode
	expressBind.FirstWaybillNo = expressBackBindReq.FirstWaybillNo
	expressBind.SecondCustomOrderCode = expressBackBindReq.SecondCustomOrderCode
	expressBind.SecondWaybillNo = expressBackBindReq.SecondWaybillNo
	expressBind.OrderTime = expressBackBindReq.OrderTime

	if err = l.svcCtx.Db.SaveExpressBind(expressBind); err != nil {
		logx.Errorf("保存绑定回程快递失败，请求体: %v, 错误: %v", expressBackBindReq, err)
		return bin, nil
	}

	return bin, nil
}
